
package com.rt.schedulenew.utils.util;

import org.slf4j.LoggerFactory;

import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import org.apache.http.conn.util.PublicSuffixMatcher;

import javax.net.ssl.HostnameVerifier;

import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;

import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;

import org.apache.http.util.EntityUtils;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;

import java.util.concurrent.TimeUnit;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import java.io.File;
import java.util.List;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.config.RequestConfig;
import org.slf4j.Logger;

public final class HttpUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private RequestConfig requestConfig;
    private static HttpUtil instance;

    public HttpUtil() {
        this.requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();
    }

    public static HttpUtil getInstance() {
        if (HttpUtil.instance == null) {
            HttpUtil.instance = new HttpUtil();
        }
        return HttpUtil.instance;
    }

    public String sendHttpPost(final String httpUrl) {
        final HttpPost httpPost = new HttpPost(httpUrl);
        return this.sendHttpPost(httpPost);
    }

    public String sendHttpPost(final String httpUrl, final String params) {
        final HttpPost httpPost = new HttpPost(httpUrl);
        try {
            final StringEntity stringEntity = new StringEntity(params, "UTF-8");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity((HttpEntity) stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.sendHttpPost(httpPost);
    }

    public String sendHttpPost(final String httpUrl, final Map<String, String> maps) {
        final HttpPost httpPost = new HttpPost(httpUrl);
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (final String key : maps.keySet()) {
            nameValuePairs.add((NameValuePair) new BasicNameValuePair(key, (String) maps.get(key)));
        }
        try {
            httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity((List) nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.sendHttpPost(httpPost);
    }

    public String sendHttpPost(final String httpUrl, final Map<String, String> maps, final List<File> fileLists) {
        final HttpPost httpPost = new HttpPost(httpUrl);
        final MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        for (final String key : maps.keySet()) {
            meBuilder.addPart(key, (ContentBody) new StringBody((String) maps.get(key), ContentType.TEXT_PLAIN));
        }
        for (final File file : fileLists) {
            final FileBody fileBody = new FileBody(file);
            meBuilder.addPart("files", (ContentBody) fileBody);
        }
        final HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return this.sendHttpPost(httpPost);
    }

    public String sendHttpPostBody(final String httpUrl, final String jsonStr) {
        return this.sendHttpPostBody(httpUrl, jsonStr, null);
    }

    public String sendHttpPostBody(final String httpUrl, final String jsonStr, final String timeout) {
        final long startTimeMillis = System.currentTimeMillis();
        String body = null;
        final CloseableHttpClient httpClient = HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(httpUrl);
        Long millis = 10000L;
        if (timeout != null && !"".equals(timeout)) {
            millis = TimeUnit.SECONDS.toMillis(Long.valueOf(timeout));
        }
        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(millis.intValue()).setConnectTimeout(millis.intValue()).build();
        httpPost.setConfig(requestConfig);
        final StringEntity s = new StringEntity(jsonStr, "utf-8");
        s.setContentEncoding((Header) new BasicHeader("Content-Type", "application/json"));
        httpPost.setEntity((HttpEntity) s);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute((HttpUriRequest) httpPost);
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                body = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        HttpUtil.log.info("响应耗时：{}毫秒", (Object) (System.currentTimeMillis() - startTimeMillis));
        return body;
    }

    private String sendHttpPost(final HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(this.requestConfig);
            response = httpClient.execute((HttpUriRequest) httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e3) {
                e3.printStackTrace();
            }
        }
        return responseContent;
    }

    public String sendHttpGet(final String httpUrl) {
        final HttpGet httpGet = new HttpGet(httpUrl);
        return this.sendHttpGet(httpGet);
    }

    public String sendHttpsGet(final String httpUrl) {
        final HttpGet httpGet = new HttpGet(httpUrl);
        return this.sendHttpsGet(httpGet);
    }

    private String sendHttpGet(final HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpClient = HttpClients.createDefault();
            httpGet.setConfig(this.requestConfig);
            response = httpClient.execute((HttpUriRequest) httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e3) {
                e3.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank((CharSequence) responseContent)) {
            responseContent = responseContent.replaceAll(" ", "");
        }
        return responseContent;
    }

    private String sendHttpsGet(final HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            final PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
            final DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier((HostnameVerifier) hostnameVerifier).build();
            httpGet.setConfig(this.requestConfig);
            response = httpClient.execute((HttpUriRequest) httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e3) {
                e3.printStackTrace();
            }
        }
        return responseContent;
    }

    public String sendPost(final String url, final String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            final URL realUrl = new URL(url);
            final URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex2) {
                ex2.printStackTrace();
            }
        }
        return result;
    }
}
